﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Client.Todo.Extendsions
{
    public class PassWordExtensions
    {

        #region 密码明文 - 依赖属性
        /// <summary>
        /// 密码明文 - 获取依赖属性
        /// </summary>                
        public static string GetPassWord(DependencyObject obj)
        {
            return (string)obj.GetValue(PassWordProperty);
        }

        /// <summary>
        /// 密码明文 - 设置依赖属性
        /// </summary>  
        public static void SetPassWord(DependencyObject obj, string value)
        {
            obj.SetValue(PassWordProperty, value);
        }

        /// <summary>
        /// 密码明文 - 注册依赖属性 
        /// <para>使用DependencyProperty作为MyProperty的后台存储。这支持动画、样式、绑定等。</para>
        /// </summary>
        public static readonly DependencyProperty PassWordProperty =
            DependencyProperty.RegisterAttached(
                "PassWord", 
                typeof(string), 
                typeof(PassWordExtensions),
                new FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,OnPassWordPropertyChanged));

        /// <summary>
        /// 当属性 出现变更时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void OnPassWordPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if(sender is PasswordBox passwordBox)
            {
                string? password = e.NewValue?.ToString();
                if (passwordBox.Password != password)
                {
                    passwordBox.Password = password;
                }
            }
        }
        #endregion end
    }

    public class PassWordBehavior : Behavior<PasswordBox>
    {

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PasswordChanged += AssociatedObject_PasswordChanged;
        }

        private void AssociatedObject_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if(e.OriginalSource is PasswordBox passwordBox)
            {
               var password = PassWordExtensions.GetPassWord(passwordBox);
                if(passwordBox != null && passwordBox.Password != password)
                {
                    PassWordExtensions.SetPassWord(passwordBox,passwordBox.Password);
                }
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PasswordChanged -= AssociatedObject_PasswordChanged;
        }

    }
}
